<?php
class system_controller_action_helper_adminLogin extends system_controller_action_helper_abstract {
	
	public function init() {
		
	}
	
	public function direct($args = array()) {
		if(!($user = system_user::getInstance()->getRow())) {
			$this->_exitAndShow();
			return true;
		}
		/**
		 * 安全登录验证
		 */
		$session = system_passport::getInstance()->getStorage();
		if($session->getSecurity() && $user->getSecure() != $session->getSecurity()) {
			$session->clean();
			$this->_exitAndShow('We found that your account has been logined in another location, and you have been forced to logout!');
			return true;
		}
		/**
		 * 权限分配
		 */
		$_root = $this->_controllerRoot();
		if($_root != 'index' && !$user->getPrivilege()->inController($_root)) {
			$this->_exitAndShow('Permission denied!', 'error');
			return true;
		}
		return false;
	}
	
	private function _controllerRoot() {
		$request = $this->getActionController()->getRequest()->getControllerName();
		$p = explode('_', $request);
		return strtolower($p[0]);
	}
	
	private function _exitAndShow($exception = null, $action = 'login') {
		$controller = $this->getActionController();
		$request = $controller->getRequest();
		$controller->view->exception = $exception;
		$controller->view->referer = $this->getFrontController()->getInstance()
									->getRouter()
									->assemble($request->getControllerName() . '/' . $request->getActionName(), $request->getParams());
		$request->setControllerName('index')->setActionName($action)->setDispatched(false);
	}
}
